<?php

declare (strict_types = 1);

namespace Chenm\Imi\websafe\Aop;

use Chenm\Imi\websafe\Main\Core;
use Imi\Aop\Annotation\Aspect;
use Imi\Aop\Annotation\Before;
use Imi\Aop\Annotation\PointCut;
use Imi\Aop\JoinPoint;
use Imi\RequestContext;
use Imi\Util\Http\Consts\MediaType;
use Imi\Util\Http\Consts\ResponseHeader;

/**
 * @Aspect
 */
class WebSafeAop {

    /**
     * 初始化
     * @PointCut(
     *         allow={
     *             "ImiApp\ApiServer\*\Controller\*::*",
     *         }
     * )
     * @Before
     * @param JoinPoint $a
     * @return void
     */
    public function webBefore(JoinPoint $joinPoint) {
        $obj = Core::init();
        $obj->run();
        $message = $obj->getMessage();
        if ($message) {
            /** @var \Imi\Server\Http\Message\Response $response */
            $response = RequestContext::get('response');
            if (preg_match('/html/', $message)) {
                $type   = 'text/html;charset=utf-8';
                $result = $message;
            } else {
                $type   = MediaType::APPLICATION_JSON_UTF8;
                $result = json_encode([
                    'code'    => 403,
                    'message' => $message,
                    'times'   => time(),
                ], JSON_UNESCAPED_UNICODE);
            }
            $response->withStatus(200)->withHeader(ResponseHeader::CONTENT_TYPE, $type)->getBody()->write($result);
            $response->send();
        }
    }
}
